<template>
  <div class="login">
    <h3>用户登录</h3>
    <el-form ref="formRef" :model="form" :rules="formRules">
      <el-form-item prop="username">
        <el-input prefix-icon="el-icon-user" v-model="form.username" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input prefix-icon="el-icon-lock" type="password" v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item class="btns">
        <el-button size="medium" type="primary" @click="submitLoginForm">登录</el-button>
        <el-button size="medium" type="danger" @click="resetLoginForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据
      form: {
        username: 'admin',
        password: '123456'
      },
      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //登录
    submitLoginForm() {
      this.$refs.formRef.validate(async valid => {
        console.log(valid);
        if (!valid) return
        // 发送登录请求
        const { data: res } = await this.$axios.post('login',this.form)
        if (res.meta.status !== 200) return this.$message.error('登录失败')
        this.$message({message: '登录成功',type: 'success'})
        // 保存用户名
        window.sessionStorage.setItem("user", this.form.username)
        //登录成功后保存token
        window.sessionStorage.setItem("token", res.data.token)
        //进行页面跳转
        this.$router.push("/home")
      })
    },
    //表单数据重置
    resetLoginForm(){
      this.$refs.formRef.resetFields()
    }
  }
}
</script>

<style scoped>
.login {
  width: 300px;
  padding: 15px 15px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgb(0, 0, 0);
  background: #fff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
h3 {
  color: #444;
}
.btns {
  display: flex;
  justify-content: flex-end;
}
</style>